package com.smday.stack;

import java.util.Stack;

/**
 * @author Summerday
 */
public class SingleLinkedStack {
    private int maxSize;

    private Node head;

    public SingleLinkedStack(int maxSize) {
        this.maxSize = maxSize;
        this.head = new Node(-1);
    }

    public boolean isFull() {
        return getSize() == maxSize;
    }

    public boolean isEmpty() {
        return getSize() == 0;
    }

    //获取top节点
    private Node getTop() {
        Node temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        return temp;
    }

    public void push(int data) {

        if (isFull()) {
            System.out.println("已满");
            return;
        }
        //创建新节点
        Node newNode = new Node(data);
        Node top = getTop();
        top.next = newNode;

    }

    public int pop() {

        if (isEmpty()) {
            throw new RuntimeException("为空");

        }
        Node curr = head.next;
        Node top = getTop();
        int data = top.data;
        System.out.printf("pop -->  %d\n", data);
        //找到top节点的前一个节点,将next指向null,不能仅仅认为将top置为null就o。
        while (curr.next != top) {
            curr = curr.next;
        }
        curr.next = null;
        return data;
    }

    public void show() {
        //下面这部分是反转链表,但会导致数据结构变化.
/*        if(isEmpty()){
            System.out.println("为空");
            return;
        }
        Node reserveHead = new Node(-1);
        Node temp = head.next;
        Node next;
        while(temp!=null){
            next = temp.next;
            temp.next = reserveHead.next;
            reserveHead.next = temp;
            temp = next;
        }
        head.next = reserveHead.next;

        list(head);*/

        //使用stack
        Node cur = head.next;

        Stack<Integer> stack = new Stack<>();
        while (cur != null) {

            stack.push(cur.data);
            cur = cur.next;
        }

        while (stack.size() > 0) {
            System.out.printf("         %d\n", stack.pop());
        }

    }

    private void list(Node head) {
        Node temp = head.next;

        while (temp != null) {
            System.out.printf("         %d\n", temp.data);
            temp = temp.next;
        }


    }

    private int getSize() {
        int size = 0;
        Node temp = head;
        while (temp.next != null) {
            size++;
            temp = temp.next;
        }
        return size;
    }
}

class Node {

    int data;
    Node next;

    public Node(int data) {
        this.data = data;
    }
}

class Test {


    public static void main(String[] args) {
        SingleLinkedStack stack = new SingleLinkedStack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);

        stack.show();
        stack.push(1);
        stack.pop();
        stack.show();


    }
}